#include <iostream>
#include <pthread.h>
#include <unistd.h>

pthread_mutex_t mutex_ = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond1_ = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond2_ = PTHREAD_COND_INITIALIZER;

int pthreadNum = 1;
using namespace std;

void *waitCommand1(void *args)
{
    while (1)
    {
        pthread_mutex_lock(&mutex_);
        while (pthreadNum == 1)
        {
            cout << "我是线程A" << endl;
            pthreadNum = 2;
            pthread_cond_wait(&cond1_, &mutex_);
        }
        pthread_mutex_unlock(&mutex_);
        pthread_cond_signal(&cond2_);
    }
}

void *waitCommand2(void *args)
{
    while (1)
    {
        pthread_mutex_lock(&mutex_);
        while (pthreadNum == 2)
        {
            cout << "我是线程B" << endl;
            pthreadNum = 1;
            pthread_cond_wait(&cond2_, &mutex_);
        }
        pthread_mutex_unlock(&mutex_);
        pthread_cond_signal(&cond1_);
    }
}

int main()
{
    pthread_t pid1, pid2;
    pthread_create(&pid1, nullptr, waitCommand1, nullptr);
    pthread_create(&pid2, nullptr, waitCommand2, nullptr);

    while (1)
    {
        pthread_cond_signal(&cond1_);
        sleep(1);
    }
    pthread_mutex_destroy(&mutex_);

    pthread_cond_destroy(&cond1_);
    pthread_cond_destroy(&cond2_);

    pthread_join(pid1, nullptr);
    pthread_join(pid2, nullptr);

    return 0;
}